import type {
  User,
  Novel,
  Chapter,
  Comment,
  PaymentRecord,
  RechargePackage,
  NovelCategory,
  NovelStatus,
} from '@/types'
// @ts-ignore
import mammoth from 'mammoth'

// 小说解析结果类型
interface NovelParseResult {
  novel: Omit<
    Novel,
    'id' | 'authorId' | 'rating' | 'ratingCount' | 'viewCount' | 'favoriteCount'
  >
  chapters: Omit<Chapter, 'id' | 'novelId' | 'chapterNumber' | 'isFree'>[]
}

// 创建小说时的数据类型
interface NovelData
  extends Omit<
    Novel,
    'id' | 'rating' | 'ratingCount' | 'viewCount' | 'favoriteCount'
  > {}

// 章节创建时的数据类型
interface ChapterData extends Omit<Chapter, 'id' | 'novelId' | 'isFree'> {
  order: number
}

// 解析小说文件
export const parseNovelFile = async (file: File): Promise<NovelParseResult> => {
  try {
    console.log('开始解析文件:', file.name)
    console.log('文件类型:', file.type)
    console.log('文件大小:', file.size)

    let content: string

    // 根据文件类型选择解析方式
    if (
      file.name.toLowerCase().endsWith('.docx') ||
      file.type ===
        'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
    ) {
      // 解析Word文档
      console.log('检测到Word文档，使用mammoth解析')
      const arrayBuffer = await file.arrayBuffer()
      const result = await mammoth.extractRawText({ arrayBuffer })
      content = result.value

      if (result.messages && result.messages.length > 0) {
        console.log('Word解析警告:', result.messages)
      }
    } else if (
      file.name.toLowerCase().endsWith('.txt') ||
      file.type === 'text/plain'
    ) {
      // 解析TXT文件
      console.log('检测到TXT文件')
      content = await new Promise<string>((resolve, reject) => {
        const reader = new FileReader()
        reader.onload = (e) => resolve(e.target?.result as string)
        reader.onerror = reject
        reader.readAsText(file)
      })
    } else {
      throw new Error('不支持的文件格式，请选择 .docx 或 .txt 文件')
    }

    if (!content || content.trim().length === 0) {
      throw new Error('文件内容为空或无法读取')
    }

    console.log('文件内容长度:', content.length)
    console.log('内容预览:', content.substring(0, 200))

    // 预处理内容
    const lines = content
      .split(/\r?\n/)
      .map((line) => line.trim())
      .filter((line) => line.length > 0)

    console.log('预处理后行数:', lines.length)

    // 从文件名提取小说标题
    const fileName = file.name.replace(/\.(docx|txt)$/i, '')

    // 查找章节
    const chapters: ChapterData[] = []
    let currentChapter: Partial<ChapterData> | null = null
    let chapterIndex = 1

    // 改进的章节标题匹配模式
    const chapterPatterns = [
      /^第[一二三四五六七八九十百千万\d]+章[\s\S]*$/, // 第X章 标题
      /^第[一二三四五六七八九十百千万\d]+回[\s\S]*$/, // 第X回 标题
      /^[一二三四五六七八九十百千万\d]+[\s\.、]{1,2}[\s\S]*$/, // X. 标题 或 X、标题
      /^章节[一二三四五六七八九十百千万\d]+[\s\S]*$/, // 章节X
      /^[Cc]hapter\s*[一二三四五六七八九十百千万\d]+[\s\S]*$/i, // Chapter X
    ]

    const isChapterTitle = (line: string): boolean => {
      return chapterPatterns.some((pattern) => pattern.test(line))
    }

    console.log('开始识别章节...')

    for (let i = 0; i < lines.length; i++) {
      const line = lines[i]

      if (isChapterTitle(line)) {
        // 保存之前的章节
        if (currentChapter && currentChapter.title && currentChapter.content) {
          if (currentChapter.content.length >= 10) {
            // 只保留有效长度的章节
            chapters.push({
              title: currentChapter.title,
              content: currentChapter.content,
              order: chapterIndex,
              chapterNumber: chapterIndex,
              wordCount: currentChapter.content.length,
              isVip: false,
              price: 0,
              createdAt: new Date().toISOString(),
              updatedAt: new Date().toISOString(),
            })
            chapterIndex++
          }
        }

        // 开始新章节
        currentChapter = {
          title: line,
          content: '',
        }
        console.log(`发现章节: ${line}`)
      } else if (currentChapter) {
        // 添加到当前章节内容
        if (currentChapter.content) {
          currentChapter.content += line + '\n'
        } else {
          currentChapter.content = line + '\n'
        }
      }
    }

    // 处理最后一个章节
    if (currentChapter && currentChapter.title && currentChapter.content) {
      if (currentChapter.content.length >= 10) {
        chapters.push({
          title: currentChapter.title,
          content: currentChapter.content,
          order: chapterIndex,
          chapterNumber: chapterIndex,
          wordCount: currentChapter.content.length,
          isVip: false,
          price: 0,
          createdAt: new Date().toISOString(),
          updatedAt: new Date().toISOString(),
        })
      }
    }

    console.log('章节识别完成，共找到:', chapters.length, '章')
    console.log(
      '章节标题列表:',
      chapters.map((ch) => ch.title)
    )

    if (chapters.length === 0) {
      // 如果没有找到章节，将整个内容作为一章
      console.log('未识别到章节结构，将整个文档作为单章节处理')
      chapters.push({
        title: '正文',
        content: content,
        order: 1,
        chapterNumber: 1,
        wordCount: content.length,
        isVip: false,
        price: 0,
        createdAt: new Date().toISOString(),
        updatedAt: new Date().toISOString(),
      })
    }

    // 计算总字数
    const totalWordCount = chapters.reduce(
      (sum, chapter) => sum + chapter.wordCount,
      0
    )
    console.log('总字数:', totalWordCount)

    // 生成小说信息
    const novel: Omit<
      Novel,
      | 'id'
      | 'authorId'
      | 'rating'
      | 'ratingCount'
      | 'viewCount'
      | 'favoriteCount'
    > = {
      title: fileName,
      author: '未知作者',
      description: `从文件《${file.name}》导入的小说，共${
        chapters.length
      }章，约${totalWordCount.toLocaleString()}字。`,
      category: 'fantasy',
      status: 'ongoing',
      wordCount: totalWordCount,
      chapterCount: chapters.length,
      cover: '/default-cover.jpg',
      tags: ['导入小说'],
      isVip: false,
      price: 0,
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString(),
    }

    console.log('解析完成:', {
      title: novel.title,
      chapterCount: novel.chapterCount,
      wordCount: novel.wordCount,
    })

    return {
      novel,
      chapters,
    }
  } catch (error) {
    console.error('文件解析错误:', error)
    throw new Error(
      `解析失败: ${error instanceof Error ? error.message : '未知错误'}`
    )
  }
}

// 模拟创建小说API
export const createNovel = async (novelData: NovelData): Promise<Novel> => {
  const novel: Novel = {
    id: Date.now().toString(),
    ...novelData,
    rating: 0,
    ratingCount: 0,
    viewCount: 0,
    favoriteCount: 0,
  }
  console.log('创建小说:', novel)
  return novel
}

// 模拟创建章节API
export const createChapters = async (
  novelId: string,
  chaptersData: ChapterData[]
): Promise<Chapter[]> => {
  const chapters: Chapter[] = chaptersData.map((chapterData, index) => ({
    id: `${novelId}_${index + 1}`,
    novelId,
    chapterNumber: index + 1,
    isFree: index < 3, // 前3章免费
    ...chapterData,
  }))
  console.log(`为小说 ${novelId} 创建 ${chapters.length} 章节`)
  return chapters
}

// 模拟数据
export const mockUsers: User[] = [
  {
    id: '1',
    email: 'admin@example.com',
    nickname: '管理员',
    password: 'admin123456',
    avatar: '/default-avatar.svg',
    level: 10,
    vipStatus: 'yearly',
    vipExpireDate: '2024-12-31',
    balance: 99999,
    readingTime: 5000,
    booksRead: 150,
    role: 'admin',
    status: 'active',
    lastLoginTime: new Date().toISOString(),
    registerIp: '127.0.0.1',
    totalRecharge: 50000,
    totalConsumption: 5000,
    purchasedChapters: [],
    createdAt: '2023-01-01T00:00:00.000Z',
    updatedAt: new Date().toISOString(),
  },
  {
    id: '2',
    email: 'user@example.com',
    nickname: '普通用户',
    password: 'user123456',
    avatar: '/default-avatar.svg',
    level: 3,
    vipStatus: 'none',
    balance: 100,
    readingTime: 120,
    booksRead: 5,
    role: 'user',
    status: 'active',
    lastLoginTime: new Date(Date.now() - 86400000).toISOString(),
    registerIp: '192.168.1.100',
    totalRecharge: 200,
    totalConsumption: 100,
    purchasedChapters: [],
    createdAt: '2023-06-15T08:30:00.000Z',
    updatedAt: new Date().toISOString(),
  },
]

// 认证API
export const login = async (email: string, password: string): Promise<User> => {
  await new Promise((resolve) => setTimeout(resolve, 1000))

  const user = mockUsers.find(
    (u) => u.email === email && u.password === password
  )
  if (!user) {
    throw new Error('邮箱或密码错误')
  }

  // 更新最后登录时间
  user.lastLoginTime = new Date().toISOString()

  // 不返回密码
  const { password: _, ...userWithoutPassword } = user
  return userWithoutPassword as User
}

export const register = async (
  email: string,
  password: string,
  nickname: string
): Promise<User> => {
  await new Promise((resolve) => setTimeout(resolve, 1000))

  if (mockUsers.find((u) => u.email === email)) {
    throw new Error('邮箱已被注册')
  }

  const newUser: User = {
    id: Date.now().toString(),
    email,
    password,
    nickname,
    avatar: '/default-avatar.svg',
    level: 1,
    vipStatus: 'none',
    balance: 0,
    readingTime: 0,
    booksRead: 0,
    role: 'user',
    status: 'active',
    registerIp: '127.0.0.1',
    totalRecharge: 0,
    totalConsumption: 0,
    purchasedChapters: [],
    createdAt: new Date().toISOString(),
    updatedAt: new Date().toISOString(),
  }

  mockUsers.push(newUser)

  const { password: _, ...userWithoutPassword } = newUser
  return userWithoutPassword as User
}
